import json

from django.http import JsonResponse
from django_redis import get_redis_connection
from rest_framework.decorators import action
from rest_framework.generics import ListAPIView, RetrieveAPIView, CreateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from question.models import Label, Question, Reply
from question.serializers import LabelsimpleSerializer, LabelSerializerWithQuestionAndArticle, QuestionSerializer, \
    QuestionSerializerForDetail, RelySerializers


# QueationSerializerForCreate, RelySerializers


class LabelsView(ListAPIView):
    #获取全部标签
    queryset = Label.objects.all()
    serializer_class = LabelsimpleSerializer
class LabelsdetailView(RetrieveAPIView):
    # 获取标签详情
    queryset = Label.objects.all()
    serializer_class =LabelSerializerWithQuestionAndArticle
    lookup_field = 'id'

class LabelCollect(RetrieveAPIView):
    # 标签关注功能
    queryset = Label.objects.all()
    serializer_class = LabelsimpleSerializer
    permission_classes = [IsAuthenticated]
    def put(self, request, id):
        label = Label.objects.get(id=id)
        label_users = label.users.all()
        if request.user in label_users:
            label.users.remove(request.user)
            label.save()
            return JsonResponse({'success': 'true', 'message': '取消收藏'})
        else:
            label.users.add(request.user)
            label.save()
            return JsonResponse({'success': 'true', 'message': '收藏成功'})

class LabelCollectnot(RetrieveAPIView):
    # 取消关注功能
    queryset = Label.objects.all()
    serializer_class = LabelsimpleSerializer
    permission_classes = [IsAuthenticated]
    def put(self,request,id):
        label = Label.objects.get(id=id)
        label_users = label.users.all()
        if request.user in label_users:
            label.users.remove(request.user)
            label.save()
            return JsonResponse({'success': 'true', 'message': '取消收藏'})
        else:
            label.users.add(request.user)
            label.save()
            return JsonResponse({'success': 'true', 'message': '收藏成功'})
class Labelusers(ListAPIView):
    #用户关注的标签
    serializer_class = LabelsimpleSerializer
    permission_classes = [IsAuthenticated]
    def get_queryset(self):
        user=self.request.user
        labels=user.labels.all()
        if labels:
            return labels
        else:
            return None

class QuestionViewSet(ModelViewSet):
    #最新回答/最热回答/等待回答问题/问题有没有用
    queryset = Question.objects.all()
    serializer_class =  QuestionSerializer
    #最新回答
    @action(methods=["GET"], detail=True, url_path="label/new")
    def get_new_question_by_labelid(self, request, pk):
        question = Question.objects.filter(reply__gte=1).order_by('-replytime')
        s =  QuestionSerializer(instance=question,many=True)
        return Response(s.data)
    @action(methods=['get'], detail=True, url_path='label/hot')
    def question_by_new(self, request, pk):
        question = Question.objects.filter(reply__gte=1).order_by('-reply')
        s =  QuestionSerializer(instance=question, many=True)
        return Response(s.data)
    # 等待回答
    @action(methods=['get'], detail=True, url_path='label/wait')
    def question_by_wait(self, request, pk):
        question = Question.objects.filter(reply=0)
        s =  QuestionSerializer(instance=question, many=True)
        return Response(s.data)

    # 问题没有用
    @action(methods=['put'], detail=True, url_path="unuseful")
    def question_by_unuserful(self, request, pk):
        # 判断用户是否存在
        try:
            user = request.user
        except:
            user = None
        if user is not None and user.is_authenticated:
            conn = get_redis_connection('question')
            flag = conn.hget(user.id, pk)
        # 获取问答的对象
            res = self.get_object()
            # 无用数加1
            if flag.decode() == 'true':
                res.unuseful_count += 1
                # 保存
                if res.useful_count>=1:
                    res.useful_count-=1
                res.save()
                conn.hset(user.id, pk, 'false')
                return Response({'success': True, 'message': '操作成功'})
            else:
                return Response({'success': False, 'message': '请不要重复操作'})
        else:
            return Response({'success': False, 'message': '未登录'}, status=400)

    # 问题有用
    @action(methods=['put'], detail=True, url_path="useful")
    def question_by_userful(self, request, pk):
        # 判断用户是否存在
        try:
            user = request.user
        except:
            user = None
        if user is not None or user.is_authenticated:
            conn=get_redis_connection('question')
            flag=conn.hget(user.id,pk)
            res = self.get_object()
            if not flag or flag.decode()=='false':
                res.useful_count += 1
                # 保存
                res.save()
            # 将数据存入redis数据库
                conn.hset(user.id, pk, 'true')
                return Response({'success': True, 'message': '操作成功'})
            else:
                return Response({'success': False, 'message': '请不要重复操作'})
        else:
            return Response({'success': False, 'message': '未登录'}, status=400)

class AddquestionView(CreateAPIView):
    # 发布问题
    queryset = Question.objects.all()
    serializer_class =  QuestionSerializer
    def post(self, request, *args, **kwargs):
        data = json.loads(request.body.decode())
        labels = data.get('labels')
        try:
            question=Question.objects.create(user=request.user,title=data['title'],content=data['content'])
        except Exception as e:
            return None
        for label in labels:
            question.labels.add(label)
        return JsonResponse({"message": "发布成功",
                             "success": "true"})

class Questiondetail(RetrieveAPIView):
    #问题详情
    queryset = Question.objects.all()
    serializer_class = QuestionSerializerForDetail
    lookup_field = 'id'
    def retrieve(self, request, id):
        question = self.get_object()
        if not question.visits:
            question.visits=0
        else:
            question.visits =question.visits
        question.visits += 1
        question.save()
        replies = question.replies.all()
        question.comment_question = []
        question.answer_question = []
        for item in replies:
            if item.type == 0:  # 问题的评论
                question.comment_question.append(item)
            elif item.type == 2:  # 回答的评论
                question.answer_question.append(item)
        s = QuestionSerializerForDetail(instance=question)
        return Response(s.data)

class ReplyViewSet(ModelViewSet):
    #评论问题
    queryset = Reply.objects.all()
    serializer_class = RelySerializers
    def create(self, request, *args, **kwargs):
        # 判断用户是否存在
        try:
            user = request.user
        except:
            user = None
        if user is not None or user.is_authenticated:
            re = request.data
            re['user'] = user.id
            ser = RelySerializers(data=re)
            ser.is_valid(raise_exception=True)
            reply = ser.save()
            problem = reply.problem
            if request.data.get('type') == 2:
                problem.reply += 1
                problem.replyname = reply.user.username
                problem.replytime = reply.createtime
                problem.save()
            return Response({'sucess':True,'message':'增加成功'})
        else:
            return Response({'success': False, 'message': '未登录'}, status=400)
    #回答没用
    @action(methods=['put'],detail=True,url_path="unuseful")
    def Reply_by_unuserful(self,request,pk):
        # 判断用户是否存在
        try:
            user = request.user
        except:
            user = None
        if user is not None or user.is_authenticated:
            conn = get_redis_connection('question')
            flag = conn.hget("reply%s" % user.id, pk)
            # 获取问答的对象
            res = self.get_object()
            # 无用数加1
            if flag.decode() == 'false':
                res.unuseful_count += 1
                # 保存
                if res.useful_count >= 1:
                    res.useful_count -= 1
                res.save()
                conn.hset("reply%s"%user.id, pk, 'true')
                return Response({'success': True, 'message': '操作成功'})
            else:
                return Response({'success': False, 'message': '请不要重复操作'})
        else:
            return Response({'success': False, 'message': '未登录'}, status=400)
    #回答有用
    @action(methods=['put'],detail=True,url_path="useful")
    def Reply_by_userful(self,request,pk):
        # 判断用户是否存在
        try:
            user = request.user
        except:
            user = None
        if user is not None or user.is_authenticated:
            conn = get_redis_connection('question')
            flag = conn.hget("reply%s"%user.id, pk)
            res = self.get_object()
            if not flag or flag.decode() == 'true':
                res.useful_count += 1
                # 保存
                res.save()
                # 将数据存入redis数据库
                conn.hset("reply%s"%user.id, pk, 'false')
                return Response({'success': True, 'message': '操作成功'})
            else:
                return Response({'success': False, 'message': '请不要重复操作'})
        else:
            return Response({'success': False, 'message': '未登录'}, status=400)

